
/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HongJuZi Framework
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */

HHJsLib.register({
    init: function() {
        this.bindBtnGoodsAdd('a.btn-goods-add');
        this.bindBtnAddNewGoodsType();
        this.bindInfoFromSubmit();
        this.bindBtnInfoFormSubmit();
        this.bindWxtuwenItem();
        this.bindBtnItemDel();
        this.bindShowData();
        this.bindBtnSave();
    },
    bindInfoFromSubmit: function() {
        $('#info-form').submit(function() {
            $('div.dd').each(function() {
                var $this       = $(this);
                var obj         = $this.nestable('serialize');
                var str         = JSON.stringify(obj);
                $this.find('input:hidden').val(str);
            });
        });
    },
    bindBtnGoodsSearchFormSubmit: function() {
        var self    = this;
        $('#goods-search-form').submit(function() {
            self.doSearchQueList(1);
            return false;
        });
    },
    doSearchQueList: function(page) {
        var self            = this;
        try {
            var keywords    = $('#goo-keywords').val();
            var type        = $('#goo-type').val();
            if(!keywords && !type) {
                throw {dom: $('#goo-keywords'), message: '搜索条件不能全为空哦！'}
            }
            $.getJSON(
                queryUrl + 'admin/articlewx/asearch',
                {keywords: keywords, type: type, page: page},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $('#search-page').val(page + 1);
                    var tableTpl    = $('#search-result-template').html();
                    var itemHtml    = self.getSearchGoodsListHtml(response.data);
                    tableTpl        = tableTpl.replace(/{content}/g, itemHtml);
                    $('#goods-table-box').html(tableTpl);
                    HHJsLib.bindLightBox('#goods-table-box a.lightbox', cdnUrl + 'jquery/plugins/lightbox');
                    self.initSearchTablePages(page, response);
                    self.bindBtnAddSearchGoodsToActivity();
                    self.bindBtnPreNextSearchPages(function(page) {
                        self.doSearchQueList(page);
                    });
                },
                'JSON'
            );
            return false;
        } catch(e) {
            return HHJsLib.warn(e);
        }
    },
    initSearchTablePages: function(page, response) {
        var prePage     = page - 1 > 0 ? page - 1 : 1;
        var nextPage    = page + 1 > response.totalPages ? response.totalPages : page + 1;
        $('#btn-btn-search-pre-page').attr('data-page', prePage);
        $('#btn-btn-search-next-page').attr('data-page', nextPage);
        $('#cur-page-info').html(page + ' / ' + response.totalPages);
        $('#btn-search-next-page,#btn-search-pre-page').attr('disabled', null);
        if(1 == response.totalPages) {
            $('#btn-search-next-page,#btn-search-pre-page').attr('disabled', 'disabled');
        } else if(1 >= page) {
            $('#btn-search-pre-page').attr('disabled', 'disabled');
        } else if (page == response.totalPages) {
            $('#btn-search-next-page').attr('disabled', 'disabled');
        }
    },
    bindBtnPreNextSearchPages: function(callback) {
        $('#btn-search-next-page,#btn-search-pre-page').click(function() {
            if(null != $(this).attr('disabled')) {
                return false;
            }
            var page    = $(this).attr('data-page');
            if('undefined' !== typeof(callback)) {
                return callback(page);
            }
        });
    },
    bindBtnAddSearchGoodsToActivity: function() {
        var self    = this;
        $('#goods-table-box a.btn-add-search-goo').click(function() {
            var id  = $(this).attr('data-id');
            var content = $('#content-' + id).html();
            var curId   = $('#cur-id').val();
            HHJsLib.editor['wx-content'].setContent(content, true);
            $('#article_content-' + curId).val(content);
            $('#search-goo-item-' + id).fadeOut('fast', function() {
                $(this).remove();
            });
        });
    },
    bindBtnGoodsItemDel: function(dom) {
        var self    = this;
        $(dom).click(function() {
            var id  = $(this).attr('data-id');
            if(!confirm('您真的要删除此项吗？注意：删除后将无法找回！')) {
                return false;
            }
            var $parent     = $('#goods-' + id);
            var status      = $parent.attr('data-status');
            if(1 == status) {
                $parent.fadeOut('fast', function() {
                    $(this).remove();
                });
                return;
            }
            HHJsLib.info('正在努力删除中...');
            var title   = $(this).parents('div.goods-list-box').siblings('div.control-group').find('input[name="title[]"]').val()
            $.getJSON(
                queryUrl + 'admin/couxiao/adelbyactitem',
                {id: id, act_id: $('#id').val(), title: title},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $parent.fadeOut('fast', function() {
                        $(this).remove();
                    });
                }
            );
        });
    },
    getSearchGoodsListHtml: function(list) {
        if(!list || 1 > list.length) {
            return '<tr><td colspan="4"><div  class="text-center">没有搜索到相关数据哦～</div></td></tr>';
        }
        var itemTpl = $('#result-item-template').html();
        var tdHtml  = '';
        for(var ele in list) {
            var item    = list[ele];
            tdHtml      += itemTpl.replace(/{id}/g, item.id)
            .replace(/{name}/g, item.name)
            .replace(/{src}/g, item.image_path)
            .replace(/{img}/g, item.small_img)
            .replace(/{content}/g, item.content);
        }

        return tdHtml;
    },
    bindBtnGoodsAdd: function(dom) {
        var self    = this;
        $(dom).click(function() {
            var id  = $(this).attr('data-id');
            var body= $('#search-goods-body-template').html();
            $('#modal-body').html(body);
            $('#myModalLabel').html('添加正文内容');
            $('#modal-footer').html($('#search-footer-template').html());
            $('#myModal').modal('show');
            self.bindBtnGoodsSearchFormSubmit();
        });
    },
    bindBtnGoodsDel: function(dom) {
        $(dom).click(function() {
            if(!confirm('您真的要删除此项吗？注意：删除后将不能恢复哦！')) {
                return;
            }
            var id      = $(this).attr('data-id');
            $('#panel-' + id).fadeOut('fast', function() {
                $(this).remove();
            });
        });
    },
    bindBtnAddNewGoodsType: function() {
        var self    = this;
        $('#btn-add-new-goods-type').click(function() {
            var total = parseInt($('.mp-news').length);
            if(total > 7){
                alert('图文内容最多8个');
                return false;
            }
            $('.wxtuwen-item').removeClass('active');
            var t   = (new Date()).getTime();
            var tpl = $('#goods-type-template').html();
            tpl     = tpl.replace(/{id}/g, t);
            $('.wxtuwen').append(tpl);
            $('.wx-title').val('');
            $('.wx-author-name').val('');
            $('.wx_image_path').val('').attr('data-url', '');
            $('.lightbox').find('img').attr('src', '');
            $('#content-msg').empty().attr('data-id', '');
            self.bindWxtuwenItem();
            $('.wxtuwen-item-' + t).trigger('click');
            formData['wx_image_path-' + t]        = {
                'timestamp' : '14842055286398',
                'token'     : 'cc130aeea1e105878a0ed9b314a95907',
                'model'     : 'articlewx',
                'field'     : 'image_path',
                'nolinked'  : 1
            };
            self.bindBtnItemDel();
        });
    },
    bindBtnInfoFormSubmit: function(){
        $("#info-form").bind('submit', function(){
            try{

            }catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindWxtuwenItem: function(){
        var self    = this;
        $('.wxtuwen-item').click(function() {
            if($(this).hasClass('active')){
                return false;
            }
            $('.wxtuwen-item').removeClass('active');
            $(this).addClass('active');
            var id      = $(this).attr('data-id');
            $('#cur-id').val(id);
            var title   = $('#title-' + id).val();
            var author  = $('#author_name-' + id).val();
            var image   = $('#image_path-' + id).val();
            var show    = $('#show_cover-' + id).val();
            var artid   = $('#article_id-' + id).val();
            var artcont = $('#article_content-' + id).val();
            $('.wx-title').val(title).attr('id', 'wx-title-' + id);
            $('.wx-author-name').val(author).attr('id', 'wx-author-name-' + id);
            $('.wx-source-url').val($('#source_url-' + id).val());
            $('.digest').val($('#digest-' + id).val());
            HHJsLib.editor['wx-content'].setContent(artcont);
            $('.btn-goods-add').attr('data-id', id);
            $('.btn-file').attr('data-target', 'wx_image_path-' + id);
            $('.wx_image_path').attr('id', 'wx_image_path-' + id);
            var dataUrl     = $('#pic-' + id).find('img').attr('src');
            $('.wx_image_path').val($('#image_path-' + id).val()).attr('data-url', dataUrl);
            $('.lightbox').attr('id', 'wx_image_path-' + id + '-lightbox');
            if(typeof dataUrl != 'undefined' && dataUrl != '' && dataUrl != null){
                $('.lightbox').html('<img src="' + dataUrl + '">');
            }else{
                $('.lightbox').html('<img src="">');
            }
        });
    },
    bindShowData: function(){
        var self = this;
        setInterval(function(){
            self.addRightToLeft();
        }, 3000);
    },
    addRightToLeft: function(){
        var id  = 0;
        $('.wxtuwen-item').each(function(){
            if($(this).hasClass('active')){
                id = $(this).attr('data-id');
                return false;
            }
        });
        if(id == 0){
            return false;
        }
        this.syncWxFormData(id);
    },
    bindBtnSave: function(){
        var self    = this;
        $('#btn-save').click(function(){
            var pass    = self.verifyWxtuwenData();
            if(pass == false){
                return false;
            }
            self.syncWxFormData($('#cur-id').val());
            var result = self.saveWxtuwenData();
        });
    },
    syncWxFormData: function(id) {
        var url = $('#wx_image_path-' + id).attr('data-url');
        var pic = '<img src="' + url + '" class="img-polaroid">';
        if(typeof url != 'undefined' && url != '' && url != null){
            $('#pic-' + id).find('img').attr('src', url);
        }
        $('#show-title-' + id).html($('.wx-title').val());
        $('#title-' + id).val($('.wx-title').val());
        $('#author_name-' + id).val($('.wx-author-name').val());
        $('#source_url-' + id).val($('.wx-source-url').val());
        $('#digest-' + id).val($('.digest').val());
        $('#image_path-' + id).val($('.wx_image_path').val());
        $('#article_id-' + id).val($('#content-msg').attr('data-id'));
        $('#article_content-' + id).val(HHJsLib.editor['wx-content'].getContent());
    },
    bindBtnMessageSearchFormSubmit: function() {
        var self    = this;
        $('#user-search-form').submit(function() {
            self.doMessageSearchQueList(1);
            return false;
        });
    },
    doMessageSearchQueList: function(page) {
        var self            = this;
        try {
            var username    = $('#message-user-name').val();
            var type        = $('#message-user-type').val();
            $.getJSON(
                queryUrl + 'admin/articlewx/auser',
                {keywords: username, type: type, page: page},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $('#message-search-page').val(page + 1);
                    var tableTpl    = $('#user-search-result-template').html();
                    var itemHtml    = self.getUserSearchGoodsListHtml(response.data);
                    tableTpl        = tableTpl.replace(/{content}/g, itemHtml);
                    $('#user-table-box').html(tableTpl);
                    self.initUserSearchTablePages(page, response);
                    self.bindBtnAddSearchGoodsToActivity();
                    self.bindBtnPreNextUserSearchPages(function(page) {
                        self.doMessageSearchQueList(page);
                    });
                },
                'JSON'
            );
            return false;
        } catch(e) {
            return HHJsLib.warn(e);
        }
    },
    getUserSearchGoodsListHtml: function(list) {
        if(!list || 1 > list.length) {
            return '<tr><td colspan="4"><div  class="text-center">没有搜索到相关数据哦～</div></td></tr>';
        }
        var itemTpl = $('#user-result-item-template').html();
        var tdHtml  = '';
        for(var ele in list) {
            var item    = list[ele];
            tdHtml      += itemTpl.replace(/{id}/g, item.id)
            .replace(/{name}/g, item.name)
            .replace(/{status}/g, item.is_subscribe);
        }

        return tdHtml;
    },
    initUserSearchTablePages: function(page, response) {
        var prePage     = page - 1 > 0 ? page - 1 : 1;
        var nextPage    = page + 1 > response.totalPages ? response.totalPages : page + 1;
        $('#btn-user-pre-page').attr('data-page', prePage);
        $('#btn-user-next-page').attr('data-page', nextPage);
        $('#cur-message-page-info').html(page + ' / ' + response.totalPages);
        $('#btn-user-next-page,#btn-user-pre-page').attr('disabled', null);
        if(1 == response.totalPages) {
            $('#btn-user-next-page,#btn-user-pre-page').attr('disabled', 'disabled');
        } else if(1 >= page) {
            $('#btn-user-pre-page').attr('disabled', 'disabled');
        } else if (page == response.totalPages) {
            $('#btn-user-next-page').attr('disabled', 'disabled');
        }
    },
    bindBtnPreNextUserSearchPages: function(callback) {
        $('#btn-user-next-page,#btn-user-pre-page').click(function() {
            if(null != $(this).attr('disabled')) {
                return false;
            }
            var page    = $(this).attr('data-page');
            if('undefined' !== typeof(callback)) {
                return callback(page);
            }
        });
    },
    verifyWxtuwenData: function(){
        var pass    = true;
        var message = '';
        $('.wxtuwen-item').each(function(){
            var id      = $(this).attr('data-id');
            var title   = $('#title-' + id).val();
            var author  = $('#author_name-' + id).val();
            var image   = $('#image_path-' + id).val();
            var content = HHJsLib.editor['wx-content'].getContent();
            if(typeof title == 'undefined' || title == ''){
                pass    = false;
                message = '请输入标题';
                $('.wxtuwen-item-' + id).trigger('click');
                return false;
            }
            if(typeof image == 'undefined' || image == ''){
                pass    = false;
                message = '请上传封面图片';
                $('.wxtuwen-item-' + id).trigger('click');
                return false;
            }
            if(typeof content == 'undefined' || content == ''){
                pass    = false;
                message = '请添加正文内容';
                $('.wxtuwen-item-' + id).trigger('click');
                return false;
            }
        });
        if(pass == false){
            return HHJsLib.warn(message);
        }

        return pass;
    },
    saveWxtuwenData: function(){
        HHJsLib.info('正在保存您的信息中，请稍等...');
        $.post(
            queryUrl + 'admin/articlewx/asavetuwen',
			$("#info-form").serialize(),
            function(response){
                if(response.rs == false){
                    return HHJsLib.warn(response.message);
                }
                $('#media_id').val(response.data);
                HHJsLib.succeed('恭喜您，素材保存成功！');
                setTimeout(function() {
                    //window.location.reload();
                }, 1500);

                return response.data;
            },
            'json'
        );

    },
    bindBtnItemDel: function(){
        $('.btn-item-del').bind('click', function(e){
            e.stopPropagation();
            var id  = $(this).attr('data-id');
            var item = $('#id-' + id).val();
            $('.wxtuwen-item-' + id).prev('.wxtuwen-item').trigger('click');
            $('.wxtuwen-item-' + id).fadeOut('fast', function() {
                $(this).remove();
            });
            if(typeof item != 'undefined' && item != '' && item != null){
                $.getJSON(
                    queryUrl + 'admin/articlewx/adelete',
                    {id: item},
                    function(response){
                        if(response.rs == false){
                            return HHJsLib.warn(response.message);
                        }
                    }
                );
            }
        });
    }
});
